package org.example;


  class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }


public class Test3 {
    //leetcode 203 移除链表的元素 https://leetcode.cn/problems/remove-linked-list-elements/description/

    /**
     * 使用哨兵节点处理
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        ListNode phead = new ListNode();
        ListNode cur = head, ret = phead;;
        while (cur != null) {
            if (cur.val != val) {
                phead.next = cur;
                phead = cur;
            }
            cur = cur.next;
        }
        phead.next = null;
        return ret.next;
    }

    //不使用哨兵节点处理
    public ListNode removeElements1(ListNode head, int val) {
        if (head == null) return null;
        ListNode phead = head, slow = head, fast = head.next;
        while (fast != null) {
            while (fast != null && fast.val == val) {
                fast = fast.next;
            }
            slow.next = fast;
            slow = slow.next;
            if (fast != null) fast = fast.next;
        }
        while (phead != null && phead.val == val) phead = phead.next;
        return phead;
    }
}
